package com.loong.common.executor;

import com.alibaba.fastjson.JSONObject;
import com.loong.common.enumerate.ResultCode;
import com.loong.common.exception.ExceptionDTO;
import com.loong.common.exception.GlobalException;
import com.loong.common.function.CommonConsumer;
import com.loong.common.function.CommonFunction;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @Description:
 * @Author: hzp
 * @Date: 2021-1-3 12:38
 */
@Slf4j
@Component
public class BatchCommonExecutor {

    public <T> void batchExecute(Collection<T> collection, CommonConsumer<T> executor){
        List<ExceptionDTO> exceptionDTOS = new ArrayList<>();
        collection.forEach(item->{
            try {
                executor.apply(item);
            }catch (Exception e){
                log.error("批量操作出现异常:{}-->{}",item,e);
                if(e instanceof GlobalException){
                    exceptionDTOS.add(ExceptionDTO.builder()
                            .errorData(((GlobalException) e).getExtraMessage())
                            .data(item)
                            .build());
                }else {
                    exceptionDTOS.add(ExceptionDTO.builder()
                            .errorData(e.getMessage())
                            .data(item)
                            .build());
                }
            }
        });
        if(exceptionDTOS.size()>1){
            throw new GlobalException(ResultCode.BATCH_ERROR, JSONObject.toJSONString(exceptionDTOS));
        }
    }
}
